<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        {{ $t("route.DaaSDesktopPools") }}
        <i v-if="false" class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card>
          <basic-table
            tableName="dassTable"
            v-loading="loading"
            ref="table"
            :pageMethod="
              (params) => {
                params.type = 'HorizonDaas';
                if (tableSearch) {
                  params.page = 1;
                  tableSearch = false;
                }
                params.search = this.searchValue;
                if (
                  this.resource_value_system &&
                  this.resource_value_system !== 'all'
                ) {
                  params.resource_pool = this.resource_value_system;
                } else {
                  delete params.resource_pool;
                }
                if (
                  this.tenant_value_system &&
                  this.tenant_value_system !== 'all'
                ) {
                  params.resource_id = this.tenant_value_system;
                } else {
                  delete params.resource_id;
                  delete params.respurcec_type;
                }
                return $pandaApi.getDesktopPools(params);
              }
            "
          >
            <template #table-options="tableSlotData">
              <!-- 搜索 -->
              <div class="table-left-options">
                <el-button
                  class="icon-button setting-button"
                  style="width: auto; margin-right: 10px"
                  @click="syncDesktopPool"
                  :loading="syncLoading"
                  :disabled="syncLoading"
                  v-if="isAll"
                >
                  <i
                    v-show="!syncLoading"
                    class="iconfont iconzhongyiicon_tongbu"
                    style="font-size: 12px; margin-right: 5px"
                  ></i>
                  <span style="font-size: 12px">{{
                    $t("desktopManage.operation.synchronizeNow")
                  }}</span>
                </el-button>
              </div>
              <div class="table-right-options">
                <el-select
                  style="margin-right: 10px"
                  filterable
                  default-first-option
                  size="medium"
                  v-model="resource_value_system"
                  @change="getResourceData(true)"
                  :placeholder="$t('desktopManage.message.selectPool')"
                  :disabled="resource_pool_loading"
                >
                  <template v-if="resource_pool_loading" #prefix>
                    <i class="el-input__icon el-icon-loading"></i>
                  </template>
                  <el-option
                    v-for="(item, index) in resource_options"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="margin-right: 10px"
                  size="medium"
                  filterable
                  default-first-option
                  :disabled="
                    tenant_value_system === 'all' || resource_tenant_loading
                  "
                  v-model="tenant_value_system"
                  @change="tableSlotData.table.refresh(true)"
                  :placeholder="$t('desktopManage.message.selectUser')"
                >
                  <template v-if="resource_tenant_loading" #prefix>
                    <i class="el-input__icon el-icon-loading"></i>
                  </template>
                  <el-option
                    v-for="(item, index) in tenant_options"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-input
                  :placeholder="$t('desktopManage.message.searchPools')"
                  v-model="searchValue"
                  style="width: 200px"
                  :disabled="loading"
                  @keyup.enter.native="tableSearchChange(tableSlotData)"
                >
                </el-input>
                <el-button
                  @click="tableSearchChange(tableSlotData)"
                  type="primary"
                  style="margin-left: 10px"
                  >{{ $t("common.search") }}</el-button
                >
              </div>
            </template>
            <template #table-column="tableSlotData">
              <!-- <el-table-column
                type="selection"
                width="40"
                align="center"
              ></el-table-column> -->
              <!-- 资源池 -->
              <el-table-column
                prop="resource_pool_name"
                :label="$t('desktopManage.resourcePool')"
              >
              </el-table-column>
              <!-- 租户 -->
              <el-table-column
                prop="resource_name"
                :label="$t('desktopManage.daaSTenants')"
              >
              </el-table-column>
              <!-- 桌面池 -->
              <el-table-column
                prop="name"
                :label="$t('desktopManage.desktopPool')"
              >
              </el-table-column>
              <!-- 操作系统 -->
              <el-table-column
                prop="os_type"
                :label="$t('desktopManage.operatingSystem')"
              >
              </el-table-column>
              <!-- 桌面数量 -->
              <el-table-column
                prop="desktop_num"
                :label="$t('desktopManage.desktop')"
              >
              </el-table-column>
              <!-- 状态 -->
              <el-table-column
                prop="online"
                :label="$t('desktopManage.status')"
                :formatter="
                  (row, column) => {
                    if (row.online === true) {
                      return $t('desktopManage.online').toString();
                    } else if (row.online === false) {
                      return $t('desktopManage.offline').toString();
                    }
                    return '';
                  }
                "
              >
              </el-table-column>
              <el-table-column :label="$t('common.action')" width="150">
                <!-- 管理桌面 -->
                <template #default="props">
                  <link-button
                    :content="$t('desktopManage.operation.managementDesktop')"
                    :size="10"
                    :font-size="'12px'"
                    @click="
                      $router.push({
                        name: 'DaaSDesktopPoolDetail',
                        query: {
                          poolid: props.row.id,
                        },
                      })
                    "
                  />
                </template>
              </el-table-column>
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import LinkButton from "../../../../components/Basic/Button/LinkButton.vue";
import BasicTable from "../../../../components/Basic/Table/BasicTable.vue";
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
  },
  data() {
    return {
      searchValue: "",
      resource_value_system: "",
      tenant_value_system: "",
      resource_options: [],
      tenant_options: [],
      loading: false,
      tableSearch: false,
      resource_pool_loading: false,
      resource_tenant_loading: false,
      isAll: false,
      syncLoading: false,
    };
  },
  watch: {
    resource_value_system(val, oldVal) {
      if (val == "all") {
        (this as any).isAll = false;
      } else {
        (this as any).isAll = true;
      }
    },
  },
  async created() {
    (this as any).getResourceData(false);
  },
  // beforeDestroy() {
  //   localStorage.setItem("resource_value_system", this.resource_value_system);
  //   localStorage.setItem("tenant_value_system", this.tenant_value_system);
  // },
  methods: {
    // 页面刷新重置page
    tableSearchChange(table: any) {
      (this as any).tableSearch = true;
      table.table.refresh(true);
    },
    syncDesktopPool() {
      // 桌面池同步
      this.syncLoading = true;
      (this as any).$pandaApi
        .syncDaaSDesktopPools(
          this.resource_value_system,
          this.tenant_value_system
        )
        .then((res: any) => {
          this.syncLoading = false;
          // (this.$refs["table"] as any).loading = false;
          try {
            (this.$refs["table"] as any).refresh();
          } catch (error) {}
          this.$message({
            message: this.$t("desktopManage.message.syncSuccess").toString(),
            type: "success",
          });
        })
        .catch(() => {
          this.syncLoading = false;
          // (this.$refs["table"] as any).loading = false;
          try {
            (this.$refs["table"] as any).refresh();
          } catch (error) {}
          this.$message({
            message: this.$t("desktopManage.message.syncFail").toString(),
            type: "warning",
          });
        });
    },
    getResourceType(id: any) {
      // 获取资源租户的resource_type
      let type = "";
      this.tenant_options.forEach((item: any) => {
        if (item.id === id) {
          type = item.resource_type;
        }
      });
      return type;
    },
    // 获取资源池数据 isSelect 是否通过选择框调用
    getResourceData(isSelect: boolean) {
      this.resource_pool_loading = true;
      (this as any).$pandaApi.apiGetResourceList().then((res: any) => {
        // 获取资源池列表
        // 初始化资源池选择数据
        this.resource_options = [];
        // 如果接口有返回数据
        if (res.length > 0) {
          res = res.sort((a: any, b: any) =>
            a.name.localeCompare(b.name, "zh-Hans-CN", {
              sensitivity: "accent",
            })
          );
          res.forEach((item: any) => {
            // 如果该资源池下有daas租户
            if (item.daas_resources > 0) {
              // 判断缓存中是否存在资源池id信息并且该id是否为当前资源池id 如果是通过选择框选择，跳过
              // if (
              //   localStorage.getItem("resource_value_system") &&
              //   localStorage.getItem("resource_value_system") == item.id &&
              //   isSelect === false
              // ) {
              //   // 将缓存中的id放入选择器中的value
              //   (this as any).resource_value_system = parseInt(
              //     localStorage.getItem("resource_value_system") as any
              //   );
              // }
              // 添加资源池选择数据
              const param: any = {};
              param.name = item.name;
              param.id = item.id;
              (this.resource_options as any).push(param);
            }
          });
          // 如果上述过程没给value赋值，默认选择资源池选择数据第一个
          (this.resource_options as any).unshift({
            id: "all",
            name: this.$t("desktopManage.allResourcePool") as any,
          });
          if (this.resource_value_system === "") {
            this.resource_value_system = (this.resource_options as any)[0].id;
          }
        } else {
          (this.resource_options as any).push({
            id: "all",
            name: this.$t("desktopManage.allResourcePool") as any,
          });
          this.resource_value_system = "all";
        }
        // 获取资源租户数据
        this.getResourceTenantData(isSelect).then(() => {
          this.resource_pool_loading = false;
        });
      });
    },
    // 获取资源租户数据 isSelect 是否通过选择器选择
    async getResourceTenantData(isSelect: boolean) {
      this.resource_tenant_loading = true;
      if (this.resource_value_system === "all") {
        this.tenant_options = [];
        (this.tenant_options as any).unshift({
          id: "all",
          name: this.$t("desktopManage.allResourceTenant") as any,
        });
        this.tenant_value_system = "all";
        (this.$refs["table"] as any).refresh(true);
        this.resource_tenant_loading = false;
      } else {
        let res = await (this as any).$pandaApi.apiGetResourceTenantsList(
          this.resource_value_system,
          {}
        );
        // 获取资源租户列表
        // 初始化资源租户数据
        this.tenant_options = [];
        this.tenant_value_system = "";
        // 判断是否有数据，以下步骤与获取资源池相同
        if (res.length > 0) {
        // console.log(res);
          res = res.sort((a: any, b: any) =>
            a.name.localeCompare(b.name, "zh-Hans-CN", {
              sensitivity: "accent",
            })
          );
          res.forEach((item: any) => {
            if (item.resource_type === "HorizonDaas") {
              // if (
              //   localStorage.getItem("tenant_value_system") &&
              //   localStorage.getItem("tenant_value_system") == item.id &&
              //   isSelect === false
              // ) {
              //   (this as any).tenant_value_system = parseInt(
              //     localStorage.getItem("tenant_value_system") as any
              //   );
              // }
              const param: any = {};
              param.name = item.name;
              param.id = item.id;
              param.resource_type = item.resource_type;
              (this.tenant_options as any).push(param);
            }

            console.log(item);
          });
          if (this.tenant_value_system === "") {
            this.tenant_value_system = (this.tenant_options as any)[0].id;
          } else {
            // this.tenant_value_system = "";
          }
        } else {
          this.tenant_value_system = "";
        }
        (this.$refs["table"] as any).refresh(true);
        this.resource_tenant_loading = false;
      }
    },
  },
});
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #eff1f4;

  .page-header {
    height: 60px;
    background-color: #ffffff;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #d9d9d9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;
    }
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}
</style>

function getResourceData() {
  throw new Error('Function not implemented.');
}
